<?php

namespace services\merchant;

use common\enums\StatusEnum;
use common\models\merchant\SettleAccountRecords;
use common\components\Service;

/**
 * Class SettleAccountRecordsService
 * @package services\merchant
 * @author YiiFrame <21931118@qq.com>
 */
class SettleAccountRecordsService extends Service
{
    /**
     * @param $data
     */
    public function create($data)
    {
        $model = new SettleAccountRecords();
        $model = $model->loadDefaultValues();
        $model->attributes = $data;
        $model->save();
    }

    /**
     * @return array|\yii\db\ActiveRecord[]
     */
    public function settleAccounts()
    {
        return SettleAccountRecords::find()
            ->select([
                'merchant_id',
                'sum(product_pay_money) as product_pay_money',
                'sum(merchant_money) as merchant_money',
                'sum(platform_money) as platform_money',
                'sum(agent_money) as agent_money',
                'sum(refund_money) as refund_money',
                'sum(merchant_distribution_money) as merchant_distribution_money',
            ])
            ->where(['is_issue' => StatusEnum::DISABLED])
            ->groupBy(['merchant_id'])
            ->asArray()
            ->all();
    }

    /**
     * @param $merchant_id
     * @return int
     */
    public function issueByMerchantId($merchant_id, $settle_account_id, $settle_account_serial_number)
    {
        return SettleAccountRecords::updateAll(
            [
                'is_issue' => StatusEnum::ENABLED,
                'settle_account_id' => $settle_account_id,
                'settle_account_serial_number' => $settle_account_serial_number,
            ],
            [
                'is_issue' => StatusEnum::DISABLED,
                'merchant_id' => $merchant_id
            ]);
    }
}